package com.saifan.wyy_ov.ui.property;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ExpandableListView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.saifan.alipay.AlipayResult;
import com.saifan.alipay.AlipayUtils;
import com.saifan.wxpay.WXPayUtils;
import com.saifan.wyy_ov.R;
import com.saifan.wyy_ov.common.NetActivity;
import com.saifan.wyy_ov.config.Api;
import com.saifan.wyy_ov.data.bean.CostBean;
import com.saifan.wyy_ov.data.bean.CostInfo;
import com.saifan.wyy_ov.data.bean.PayResultBean;
import com.saifan.wyy_ov.data.bean.PropertyPayBean;
import com.saifan.wyy_ov.data.bean.RoomInfoBean;
import com.saifan.wyy_ov.model.impl.GetData;
import com.saifan.wyy_ov.model.interfaces.ResponseData;
import com.saifan.wyy_ov.ui.communitycenter.PaythefeesActivity;
import com.saifan.wyy_ov.ui.set.ServerSetActivity;
import com.saifan.wyy_ov.ui.view.MaterialDialog;
import com.saifan.wyy_ov.utils.DialogUtil;
import com.saifan.wyy_ov.utils.ToastUtil;
import com.saifan.wyy_ov.wxapi.WXPayEntryActivity;
import com.socks.library.KLog;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import net.sourceforge.simcpux.Constants;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lomasky.ma.httpUtils.JsonUtil;
import lomasky.ma.httpUtils.ResponseBean;
import lomasky.ma.utils.StringUtil;
import lomasky.ma.xui.CommonAdapter;
import lomasky.ma.xui.NoScrollListView;
import lomasky.ma.xui.ViewHolderHelper;

/**
 * @author lomasky
 * @date 2015-06-03
 * @description 费用查询
 */
public class FeeQueryActivity extends NetActivity {
    private ExpandableListView listView;
    private android.widget.CheckBox all;
    private android.widget.TextView cost;
    private LinearLayout layoutpayTip;
    private android.widget.FrameLayout totallayout;
    private android.widget.TextView textViewprepay;
    private android.widget.TextView textViewdescription;
    private android.widget.Button paybutton;
    private LinearLayout bottomlayout;
    private LinearLayout emptyView;
    private MaterialDialog dialog;
    List<CostBean> costBeen;
    private RoomInfoAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fee_query);
        roomInfoBean = getRoomInfoBean();
        this.bottomlayout = (LinearLayout) findViewById(R.id.bottom_layout);
        this.paybutton = (Button) findViewById(R.id.pay_button);
        this.textViewdescription = (TextView) findViewById(R.id.textView_description);
        this.textViewprepay = (TextView) findViewById(R.id.textView_prepay);
        this.totallayout = (FrameLayout) findViewById(R.id.total_layout);
        this.layoutpayTip = (LinearLayout) findViewById(R.id.layout_payTip);
        this.cost = (TextView) findViewById(R.id.cost);
        this.all = (CheckBox) findViewById(R.id.all);
        this.listView = (ExpandableListView) findViewById(R.id.listView);
        emptyView = (LinearLayout) getLayoutInflater().inflate(R.layout.fee_empty, null);
        ((ViewGroup) listView.getParent()).addView(emptyView);
        setEnabledNavigation(true);
        if (roomInfoBean != null) {
            Map<String, Object> params = new HashMap<>();
            params.put("WYFYSQ_FKGXWJ", roomInfoBean.FKGX_ZJ);
            params.put("XMBS", roomInfoBean.XMBS);
            post(Api.Customer.COST, params, "正在查询");
        }

        if (getIntent() != null) {
            if (getIntent().getIntExtra("payResult", -1) == 0) {
                layoutpayTip.setVisibility(View.GONE);
                listView.setVisibility(View.GONE);
                textViewdescription.setVisibility(View.GONE);
                textViewprepay.setVisibility(View.GONE);

                return;
            }
        }

        dialog = DialogUtil.createDailog(this, WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        dialog.setTitle("滞纳金说明");



    }


    public void pay(View view) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择支付类型");
        builder.setItems(new String[]{"微信支付", "支付宝支付"}, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
                creatPay(i);
            }
        });
        builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialogInterface, int keyCode, KeyEvent keyEvent) {
                switch (keyCode) {
                    case 4:
                        dialogInterface.dismiss();
                        break;
                    default:
                        break;
                }
                return true;
            }
        });
        builder.show();

    }

    private void creatPay(final int type) {
        PropertyPayBean propertyPayBean = new PropertyPayBean();
        propertyPayBean.setXMBS(String.valueOf(roomInfoBean.getXMBS()));
        propertyPayBean.setKHWJ(roomInfoBean.getWYKHDA_ZJ());
        propertyPayBean.setYZXM(roomInfoBean.getWYKHDA_KHMC());
        propertyPayBean.setFKGXWJ(roomInfoBean.getFKGX_ZJ());
        propertyPayBean.setJFLX(String.valueOf(type));
        propertyPayBean.setFJWJ(roomInfoBean.getWYFJDA_ZJ());
        propertyPayBean.setFJMC(roomInfoBean.getWYFJDA_FJMC());
        new GetData().getDataJson(FeeQueryActivity.this, Api.Cost.PROPERTY_PAY, propertyPayBean, "正在请求...", new ResponseData() {
            @Override
            public void onSuccess(String json) {
                if (type == 1) {
                    List<PayResultBean> list = JsonUtil.getList(json, PayResultBean.class);
                    if (list != null) {
                        AlipayUtils alipayUtils = new AlipayUtils();
                        alipayUtils.alipay(FeeQueryActivity.this, list.get(0).getPrepay_id(), new AlipayResult() {
                            @Override
                            public void onResult(int code) {
                                Intent intent = new Intent(FeeQueryActivity.this, WXPayEntryActivity.class);
                                intent.putExtra("pay_result", code);
                                startActivity(intent);
                            }
                        });
                    } else {
                        ToastUtil.showToast(FeeQueryActivity.this, "服务器出错了 !");
                    }
                } else {
                    List<PayResultBean> list = JsonUtil.getList(json, PayResultBean.class);
                    if (list != null) {
                        Constants.API_KEY = list.get(0).getKey();
                        Constants.APP_ID = list.get(0).getAPPID();
                        Constants.MCH_ID = list.get(0).getMCHID();
                        WXPayUtils wxPayUtils = new WXPayUtils();
                        if (!wxPayUtils.isWXAppInstalledAndSupported(FeeQueryActivity.this, WXAPIFactory.createWXAPI(FeeQueryActivity.this, null))) {
                            final MaterialDialog dialog = DialogUtil.createDailog(FeeQueryActivity.this, "提示", "您尚未安装微信");
                            dialog.setNegativeButton("确定", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {

                                    dialog.dismiss();
                                }
                            });
                            dialog.show();
                            return;
                        }
                        wxPayUtils.sendPayReq(FeeQueryActivity.this, list.get(0).getPrepay_id());
                    } else {
                        ToastUtil.showToast(FeeQueryActivity.this, "服务器出错了 !");
                    }
                }

            }

            @Override
            public void onFailed(String str) {

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_bill, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            startActivity(new Intent(this, PaythefeesActivity.class));
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void prePay(View view) {
        Intent intent = new Intent(this, CostPayActivity.class);
        intent.putExtra(RoomInfoBean.class.getSimpleName(), roomInfoBean);
        startActivity(intent);
    }

    public void descrption(View view) {
        dialog.show();


    }

    @Override
    public void err(String e) {
        if (e.equals("404")) {
            ToastUtil.showToast(this, "请设置授权项目");
            startActivity(ServerSetActivity.class);
        } else {
            showToast(e);
        }
    }

    @Override
    public void ok(ResponseBean response) {


        costBeen = JsonUtil.getList(response.content, CostBean.class);
        adapter = new RoomInfoAdapter(costBeen);
        if (!costBeen.isEmpty()&&costBeen.get(0).getCost().size()>0 ) {

            totallayout.setVisibility(View.VISIBLE);
            cost.setText(getString(R.string.rmb, StringUtil.getPrice(costBeen.get(0).getTotal())));
            dialog.setMessage(StringUtil.returnShow(costBeen.get(0).getNote()));
            listView.setAdapter(adapter);
            adapter.notifyDataSetChanged();
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) listView.getLayoutParams();
            layoutParams.setMargins(0, 0, 0, bottomlayout.getHeight());
            listView.setLayoutParams(layoutParams);
        } else {
            bottomlayout.setVisibility(View.GONE);
            cost.setText("0");
            listView.setEmptyView(emptyView);
        }




    }


    class RoomInfoAdapter extends BaseExpandableListAdapter {


        private List<CostBean> list;

        public RoomInfoAdapter(List<CostBean> list) {
            this.list = list;
        }

        //-----------------Child----------------//
        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return list.get(groupPosition).getCost().get(childPosition);
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return list.get(groupPosition).getCost().size();
        }

        @Override
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {

            final ViewHolderHelper viewHolder = ViewHolderHelper.get(FeeQueryActivity.this, convertView, parent, R.layout.fee_room_select_month_layout, groupPosition);


            viewHolder.getTextView(R.id.text_month).setText(list.get(groupPosition).getCost().get(childPosition).getTime().replace("-", "年") + "月欠费");
            NoScrollListView listView = viewHolder.getView(R.id.listView);

            CommonAdapter<CostInfo> adapter = new CommonAdapter<CostInfo>(FeeQueryActivity.this, R.layout.fee_month_list_layout) {
                @Override
                public void onBind(ViewHolderHelper holder, CostInfo item, int position) {

                    holder.setText(R.id.fee_type, item.WYFYSQ_SFXMMC);
                    holder.setText(R.id.principal, item.WYFYSQ_QSJE);
                    holder.setText(R.id.lateFees, item.WYFYSQ_ZNJQS);
                    holder.setText(R.id.total, item.WYFYSQ_HJ);
                }
            };


            listView.setAdapter(adapter);
            adapter.setData(list.get(groupPosition).getCost().get(childPosition).getCostInfo());
            adapter.notifyDataSetChanged();

            return viewHolder.getConvertView();
        }

        //----------------Group----------------//
        @Override
        public Object getGroup(int groupPosition) {
            return list.get(groupPosition);
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public int getGroupCount() {
            return list.size();
        }

        @Override
        public View getGroupView(final int groupPosition, final boolean isExpanded, View convertView, ViewGroup parent) {

            final ViewHolderHelper viewHolder = ViewHolderHelper.get(FeeQueryActivity.this, convertView, null, R.layout.fee_room_select_layout, groupPosition);

            viewHolder.setText(R.id.resName, roomInfoBean.XMDA_XMMC + roomInfoBean.getWYFJDA_FJMC());
            viewHolder.setText(R.id.total, getString(R.string.rmb, StringUtil.getPrice(list.get(groupPosition).getTotal())));
            viewHolder.getConvertView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!isExpanded) {
                        listView.expandGroup(groupPosition, true);

                    } else {
                        listView.collapseGroup(groupPosition);
                    }
                }
            });
            viewHolder.getImageView(R.id.arrows_yellow_up).setVisibility(isExpanded ? View.VISIBLE : View.GONE);
            return viewHolder.getConvertView();


        }


        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }


    }


}
